
#import "ChatViewController.h"
#import "WFLabel_blackShadow.h"
#import "PublicFun.h"
#import "FirendInfo.h"
#import "ChatCell.h"
#import "ChatContentInfo.h"
#import "imageTransfrom.h"
#import "recordManager.h"
#import "XMMessageInfo.h"
#import <QuartzCore/QuartzCore.h>
#import "SpeexCodec.h"
#import "chatuserdb.h"
#import "giftShowView.h"

#import "GiftMessageDataSource.h"
#import "GiftInfoDataSource.h"
#import "giftStroageDataSource.h"

#import "giftMessageInfo.h"
#import "GiftInfoDataInfo.h"

#import "sendPotocol.h"
#import "sendGiftGetStroage.h"
#import "sendGiftListLength.h"
#import "sendPersonReadCoin.h"

#import "chatDataSource.h"
#import "ChatGiftCell.h"
#import "GiftInfoDataSource.h"

#import "MessageDataSource.h"
#import "VoiceButtonView.h"

#define CHATCONTROL_HIGHT (WINDOW_HIGTH > 480 ? 460:376)

@implementation UIScrollView (UITouch)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesBegan:touches withEvent:event];
    [super touchesBegan:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesMoved:touches withEvent:event];
    [super touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self nextResponder] touchesEnded:touches withEvent:event];
    [super touchesEnded:touches withEvent:event];
}
@end

@implementation ChatViewController

enum ChatSheetType
{
    CST_PHOTO,
    CST_GIFT,
    CST_RESEND,
};

-(id)init
{
    self = [super init];
    if(self)
    {
        //监听键盘高度的变换
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        
        // 键盘高度变化通知，ios5.0新增的
#ifdef __IPHONE_5_0
        float version = [[[UIDevice currentDevice] systemVersion] floatValue];
        if (version >= 5.0) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
        }
#endif
        self.chatArray = [NSMutableArray array];
        self.rowHeights = [NSMutableArray array];
        NSString *emojiFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"faceMap_ch.plist"];
        NSDictionary *emojiNameDic = [[NSDictionary alloc] initWithContentsOfFile:emojiFilePath];
        
        _emojiDic = [[NSMutableDictionary alloc]init];
        for (NSString* key in [emojiNameDic allKeys]) {
            NSString *newKey = [emojiNameDic objectForKey:key];
            NSString *newObj = [NSString stringWithFormat:@"%@.png",key];
            [_emojiDic setObject:newObj forKey:newKey];
        }
        
        recordTimer = 0;
        bStartRecord = false;
        playingVoiceIndex = -1;
        
        iSheetType = CST_PHOTO;
        
        StateFailDic = [[NSMutableDictionary alloc] init];
    }
    
    return self;
}

-(void)initUI
{
    [self createTitle];
    
    if ([DataControl shareControl].currentFI != nil)
    {
        FirendInfo *fi = [[DataControl shareControl] SearchInfo:
                          [DataControl shareControl].currentFI.mail];
        if (fi != nil)
        {
            self.mtitle.text = fi.name;
        }
    }
    
    UIBarButtonItem *backItem = [self createBarBackButtonItemWithTitle:@"返回" target:self
                                                                action:@selector(backButtonPressed)];
    self.navItem.leftBarButtonItem = backItem;
    backItem = [self createBarButtonItemWithTitle:@"个人信息" target:self
                                               action:@selector(InfoButtonPressed)];
    self.navItem.rightBarButtonItem = backItem;
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WINDOW_WIDTH, 5)];
    headView.backgroundColor = [UIColor clearColor];
    
    self.mtablev =[[UITableView alloc]initWithFrame:CGRectMake(0, TOPBAR_HIGHT, WINDOW_WIDTH,
                                                          WINDOW_HIGTH - CHATVIEW_INPUTBAR_HEIGHT*2
                                                                - NATIVEBAR_HIGTH)
                                                     style:UITableViewStylePlain];
    self.mtablev.backgroundColor= [UIColor clearColor];
    self.mtablev.tableHeaderView = headView;
    self.mtablev.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.mtablev.delegate =self;
    self.mtablev.dataSource =self;
    [self.view addSubview:self.mtablev];
    
   
    
    [self createInputBar];
    [self createVoiceBtn];
}

-(void)createInputBar
{
    chatInput = [[THChatInput alloc]initWithFrame:CGRectMake(0.0f,
                                                             WINDOW_HIGTH - CHATVIEW_INPUTBAR_HEIGHT
                                                             - NATIVEBAR_HIGTH,
                                                             WINDOW_WIDTH,
                                                             44)];
    
    chatInput.backgroundColor = [UIColor clearColor];
    chatInput.inputBackgroundView.image = [[UIImage imageNamed:@"Chat_Footer_BG.png"] stretchableImageWithLeftCapWidth:110 topCapHeight:25];
    
	[chatInput.attachButton setBackgroundImage:[UIImage imageNamed:@"Chat_Footer_ArrowUp.png"] forState:UIControlStateNormal];
    [chatInput.giftButton setBackgroundImage:[UIImage imageNamed:@"chat_footer_gift.png"] forState:UIControlStateNormal];
	[chatInput.emojiButton setBackgroundImage:[UIImage imageNamed:@"Chat_Footer_Smiley_Icon.png"] forState:UIControlStateNormal];
    [chatInput.sendButton setBackgroundImage:[UIImage imageNamed:@"Chat_Send_Button.png"] forState:UIControlStateNormal];
	[chatInput.sendButton setTitle:@"发送" forState:UIControlStateNormal];
    
    chatInput.delegate = self;
    chatInput.userInteractionEnabled = YES;
    
    emojiInputView = [[FaceBoard alloc]init];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(inputEmoji:)
                                                 name:NOTIFICATION_FACE_INPUT
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(deleteEmoji:)
                                                 name:NOTIFICATION_FACE_DEL 
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(audioControlBtnPress:)
                                                 name:NOTIFICATION_VOICE_PRESS
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(chatImagePress:)
                                                 name:NOTIFICATION_IMG_PRESS
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(dismissKeyboard)
                                                 name:NOTIFICATION_CELL_PRESS
                                               object:nil];
}



-(void)createVoiceBtn
{
    voiceButton = [[VoiceButtonView alloc]initWithFrame:CGRectMake(0,
                                                                   WINDOW_HIGTH - CHATVIEW_VOICEBAR_HEIGHT - NATIVEBAR_HIGTH,
                                                                   WINDOW_WIDTH,
                                                                   CHATVIEW_VOICEBAR_HEIGHT)];
    voiceButton.image =[UIImage imageNamed:@"chatvoicebg.png"] ;
    voiceButton.userInteractionEnabled = YES;
    voiceButton.chatVCdelegate = self;
    
    UIButton *textInputBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    textInputBtn.frame = CGRectMake(4, (CHATVIEW_VOICEBAR_HEIGHT - 32)/2, 32, 32);
    [textInputBtn setBackgroundImage:[UIImage imageNamed:@"Chat_Footer_Keyboard_Icon.png"] forState:UIControlStateNormal];
    [textInputBtn addTarget:self action:@selector(showTextInput:) forControlEvents:UIControlEventTouchUpInside];
    [voiceButton addSubview:textInputBtn];
    
    UIButton *photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    photoBtn.frame = CGRectMake(284, (CHATVIEW_VOICEBAR_HEIGHT - 32)/2, 32, 32);
    [photoBtn setBackgroundImage:[UIImage imageNamed:@"Chat_Footer_Camera_Icon.png"] forState:UIControlStateNormal];
    [photoBtn addTarget:self action:@selector(showPhotoInput:) forControlEvents:UIControlEventTouchUpInside];
    [voiceButton addSubview:photoBtn];
    
}

#pragma mark -Private Fun -
-(void)backButtonPressed
{
    if (player) {
        [player stop];
    }
    
    [[DataControl shareControl] SetGameState:GMS_NULL];
    
    [[ViewManager sharedViewManager] backView:self];
}

-(void)InfoButtonPressed
{
    if (player) {
        [player stop];
    }
    
    [self dismissKeyboard];
    
    if ([DataControl shareControl].currentFI != nil) {
        [[ViewManager sharedViewManager] showView:VI_PERSONINFO
                                 withIsRemoveCurV:false
                                    withDirection:VD_RIGHT];
    }
}

-(void)addPicturePressed
{
    [self showActionView];
    
    if ([chatInput.textView isFirstResponder])
    {
        [chatInput.textView resignFirstResponder];
    }
}

-(void)pressToSay
{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
    
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    if(session == nil)
    {
        AS_LOG(@"Error creating session: %@", [sessionError description]);
    }
    else
        [session setActive:YES error:nil];
    
    if (nil == voiceTipsView) {
		voiceTipsView = [[VoiceTipsView alloc] initWithFrame:CGRectMake((320 - 184)/2, 144, 184, 184)];
	}
	[voiceTipsView showPttStartImage];
    
    [[recordManager shareControl] startRecord];
    bStartRecord = true;
    voiceRecordTimer = [NSTimer scheduledTimerWithTimeInterval:0.03
                                                        target: self
                                                      selector: @selector(levelTimerCallback:)
                                                      userInfo: nil
                                                       repeats: YES];
    recordTimer = 0;
}

- (void)sendButtonPressed:(id)sender
{    
    if ([chatInput.textView.text length] == 0)
    {
        return;
    }
    
    [self sendChatContent:chatInput.textView.text
                 withType:CT_TEXT
          withAudioLength:-1];
    
    if (![chatInput.textView.text isEqual: @""])
    {
        [[DataControl shareControl].LCDS addLogicCommand:LC_SENDTEXT];
        chatInput.textView.text = @"";
        [chatInput fitText];
    }
}

- (void)levelTimerCallback:(NSTimer *)timer {
	double power = [[recordManager shareControl] updateRecordPower];
    
    if (power == 0) {
        return;
    }
    
	int index = 0;
	if (power <= 0.1) {
		index = 1;
	}else if (power > 0.1 && power <= 0.2){
		index = 2;
	}else if (power > 0.2 && power <= 0.3){
		index = 3;
	}else if (power > 0.3 && power <= 0.4){
		index = 4;
	}else if (power > 0.4 && power <= 0.45) {
		index = 5;
	}else if (power > 0.45 && power <= 0.5){
		index = 6;
	}
	else if (power > 0.5){
		index = 7;
	}
	if (voiceTipsView) {
		[voiceTipsView updatePttSoundVolumImage:index];
	}
}

- (void) showAttachInput:(id)sender {
    
    [chatInput removeFromSuperview];
    [self.view addSubview:voiceButton];
}

- (void) showTextInput:(id)sender {
    
    [voiceButton removeFromSuperview];
    [self.view addSubview:chatInput];
}


- (void)showPhotoInput:(id)sender {
    
    [self showActionView];
}

-(void)sendChatContent:(NSString *)strcontent
              withType:(int)itype
       withAudioLength:(int)iaudiolength
{
    ChatContentInfo *cci = [[ChatContentInfo alloc] init];
    cci.chatType = itype;
    cci.strtext = strcontent;
    cci.isSelf = true;
    cci.isgroup = false;
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970] * 1000;
    long long aa = a;
    
    cci.strChatDate = [NSString stringWithFormat:@"%lld", aa];
    cci.iSequence = getLocalSequence();
    cci.ichatReadState = CRS_SENDING;
    
    if (iaudiolength != -1) {
        cci.audioPlayLength = iaudiolength;
    }
    
    [LogicControl sharedLogicControl].icurSequence = cci.iSequence;
    
    if ([DataControl shareControl].currentFI != nil)
    {
        cci.mail = [DataControl shareControl].currentFI.mail;
    }
    
    if ([[DataControl shareControl].chatDS.currentChatArr count] == 0 &&
        [DataControl shareControl].currentFI != nil)
    {
        XMMessageInfo *minfo = [[XMMessageInfo alloc] init];
        minfo.mbAlreadayArgee = true;
        minfo.messageType = XMMT_CHAT;
        minfo.strmail = [DataControl shareControl].currentFI.mail;
        minfo.mindex = [[DataControl shareControl].messageDS GetMagArrCount];
        minfo.strmsgid = [[DataControl shareControl].messageDS getMsgID];
        minfo.strtime = cci.strChatDate;
        
        [[MessageManager sharedManager] AddMessage:minfo];
    }
    
    [[DataControl shareControl].chatDS.currentChatArr addObject:cci];
    
    [[DataControl shareControl].chatDS addChatInfo:cci withSquence:cci.iSequence];
    
    [[DataBaseCtrol shareControl].chatuserdatabase insertChatInfo:cci];
    [[DataControl shareControl].chatDS SetSendChatContent:strcontent];
    [self createTextView:cci];
    [self reloadChatView];
    
    [StateFailDic setObject:[NSNumber numberWithInt:0]
                     forKey:[NSNumber numberWithInt:cci.iSequence]];
}

- (void) returnButtonPressed:(id)sender {
    
    if ([chatInput.textView.text length] == 0)
    {
        return;
    }
    
    [self sendChatContent:chatInput.textView.text
                 withType:CT_TEXT
          withAudioLength:-1];
    
    if (![chatInput.textView.text isEqual: @""])
    {
        [[DataControl shareControl].LCDS addLogicCommand:LC_SENDTEXT];
        chatInput.textView.text = @"";
        [chatInput fitText];
    }

}

-(void)soundPressed
{
    bStartRecord = false;
    if (recordTimer < 10) {
        [[recordManager shareControl] stopRecord];
        [voiceRecordTimer invalidate];
        [voiceTipsView showPttFailImage];
        [self performSelector:@selector(dismissVoiceTipsView) withObject:nil afterDelay:1.2];
    }
    else
    {
        [[recordManager shareControl] stopRecord];
        [voiceRecordTimer invalidate];
        recordTimer = 0;
        [self dismissVoiceTipsView];
        
        [self sendChatContent:[[recordManager shareControl].recordedFile path]
                     withType:CT_VOICE
              withAudioLength:[[recordManager shareControl] GetRecordLength]];
        
        [[DataControl shareControl].LCDS addLogicCommand:LC_SENDVOICE];
    }
}

-(void)dismissVoiceTipsView
{
  [voiceTipsView dismissTips];  
}

-(void)reloadChatView
{
    [self createTextArray];
    [self.mtablev reloadData];
    
    int icount = [DataControl shareControl].chatDS.currentChatArr.count - 1;
    if(icount > 0)
    {
        [self.mtablev scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:icount
                                                           inSection:0]
                       atScrollPosition: UITableViewScrollPositionBottom
                               animated:YES];
    }
}

-(void)showActionView
{
    iSheetType = CST_PHOTO;
    
    UIActionSheet *sheetPhoto=[[UIActionSheet alloc]initWithTitle:@"请选择图片来源" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
    [sheetPhoto showInView:self.view];
}

-(void)UICustomTick
{
    if (bStartRecord)
    {
        ++recordTimer;
    }
    
    if (StateFailDic.count > 0) {
        NSArray *keyarr = [StateFailDic allKeys];
        for (NSNumber *ccnum in keyarr) {
            ChatContentInfo *ccinfo = [[DataControl shareControl].chatDS
                                       getChatInfoBySequence:[ccnum intValue]];
            
            if (ccinfo != nil) {
                if (ccinfo.ichatReadState != CRS_SENDING) {
                    [StateFailDic removeObjectForKey:ccnum];
                }
                else
                {
                    NSNumber *num = [StateFailDic objectForKey:ccnum];
                    
                    if ([num intValue] > 200) {
                        ccinfo.ichatReadState = CRS_SENDFAIL;
                        
                        [[DataControl shareControl].chatDS SetModifyState:CRS_SENDFAIL];
                        [[DataControl shareControl].chatDS addModifyStateArr:ccinfo];
                        
                        [[DataControl shareControl].LCDS addLogicCommand:LC_CHAT_MODIFYSTATE];
                        
                        [StateFailDic removeObjectForKey:ccnum];
                        
                        [self.mtablev reloadData];
                    }
                    else
                    {
                        int inum = [num intValue] + 1;
                        [StateFailDic setObject:[NSNumber numberWithInt:inum] forKey:ccnum];
                    }
                    
                }
            }
            else
            {
                [StateFailDic removeObjectForKey:ccnum];
            }
            
        }
    }
}

-(void)refreshView
{
    if ([DataControl shareControl].currentFI != nil)
    {
        FirendInfo *fi = [[DataControl shareControl] SearchInfo:
                          [DataControl shareControl].currentFI.mail];
        if (fi != nil)
        {
            self.mtitle.text = fi.name;
        }
    }
    
    [self reloadChatView];
}

-(void)viewWillShow
{
    [chatInput removeFromSuperview];
    [voiceButton removeFromSuperview];
    [StateFailDic removeAllObjects];
    
    [self.view addSubview:chatInput];
    
    
    if ([DataControl shareControl].chatDS.currentChatArr != nil) {
        
        for (ChatContentInfo *ccinfo in [DataControl shareControl].chatDS.currentChatArr) {
            if (ccinfo.ichatReadState == CRS_SENDING) {
                [StateFailDic setObject:[NSNumber numberWithInt:0]
                                 forKey:[NSNumber numberWithInt:ccinfo.iSequence]];
            }
        }
        
        [[DataControl shareControl].LCDS addLogicCommand:LC_CHAT_PROCESSMSG];
    }
    
    [self refreshView];
}

-(void)viewWillHide
{
    [[DataControl shareControl] SetGameState:GMS_NULL];
    [StateFailDic removeAllObjects];
}

-(void)createTextArray
{
    [self.rowHeights removeAllObjects];
    [self.chatArray removeAllObjects];
    
    if ([DataControl shareControl].chatDS.currentChatArr == nil) {
        return;
    }
    
    for (int i = 0; i < [DataControl shareControl].chatDS.currentChatArr.count; i++) {
        ChatContentInfo *cci = [[DataControl shareControl].chatDS.currentChatArr objectAtIndex:i];
        [self createTextView:cci];
    }
}

-(void)createTextView:(ChatContentInfo *)cci
{
    float height = 31;
    if (cci.chatType == CT_TEXT ||
        cci.chatType == CT_TELEPATHY) {
        UIView *returnView =  [self getTextViewOnCell:cci.strtext];
        returnView.backgroundColor = [UIColor clearColor];
        height = returnView.frame.size.height + 10;
        [self.chatArray addObject:returnView];
    }else if (cci.chatType == CT_IMAGE) {
        
        [self.chatArray addObject:cci.strtext];
        UIImage * tmpImage = [UIImage imageWithData:
                              [NSData dataWithContentsOfFile:
                               cci.strtext]];//聊天发送的图片
        
        if (tmpImage.size.width > tmpImage.size.height) {
            height = tmpImage.size.height * 100/tmpImage.size.width;
        }else{
            height = 100;
        }
           
    }else if (cci.chatType == CT_VOICE) {
        [self.chatArray addObject:cci.strtext];
        height = 31;
    }
    else if(cci.chatType == CT_GIFT)
    {
        [self.chatArray addObject:cci.strtext];
        height = 60;
    }
    else if(cci.chatType == CT_TELEPATHY)
    {
        [self.chatArray addObject:cci.strtext];
        height = 60;
    }
    
    NSNumber *heightNum = [[NSNumber alloc] initWithFloat:height];
    [self.rowHeights addObject:heightNum];
}

-(void)longPressed:(id)sender
{
  [self pressToSay];
}

-(void)cancelLongPress:(id)sender
{
  [self soundPressed];
}

-(void)audioControlBtnPress:(NSNotification *)notification
{
    UIImageView *img = (UIImageView *)[notification object];
    ChatContentInfo *cci= [[DataControl shareControl].chatDS.currentChatArr objectAtIndex:img.tag];
    if (player) {
        if ([player isPlaying]) {
           [player stop];
            playingVoiceIndex = -1;
            img.image = [UIImage imageNamed:@"btn_audioPlay_press.png"];
        }else{
            playingVoiceIndex = img.tag;
            [self playVoice:cci.strtext];
            img.image = [UIImage imageNamed:@"btn_audioPause_press.png"];
            
            if (cci.ichatReadState == CRS_UNREAD) {
                [[DataControl shareControl].chatDS SetModifyState:CRS_READ];
                [[DataControl shareControl].chatDS addModifyStateArr:cci];
                
                [[DataControl shareControl].LCDS addLogicCommand:LC_CHAT_MODIFYSTATE];
            }
        
        }
    }else{
       playingVoiceIndex = img.tag;
       [self playVoice:cci.strtext];
       img.image = [UIImage imageNamed:@"btn_audioPause_press.png"];
        
        if (cci.ichatReadState == CRS_UNREAD) {
            [[DataControl shareControl].chatDS SetModifyState:CRS_READ];
            [[DataControl shareControl].chatDS addModifyStateArr:cci];
            
            [[DataControl shareControl].LCDS addLogicCommand:LC_CHAT_MODIFYSTATE];
        }
    }
}

-(void)chatImagePress:(NSNotification *)notification
{
    NSString *imgPath = (NSString*)[notification object];
    UIImage * tmpImage = [UIImage imageWithData:
                          [NSData dataWithContentsOfFile:
                           imgPath]];
    [[ViewManager sharedViewManager] setChatImage:tmpImage];
    if ([ViewManager sharedViewManager].currentVC !=
        (CommonViewController*)[ViewManager sharedViewManager].chatImageVC) {
        [[ViewManager sharedViewManager] showView:VI_CHATIMAGE
                                 withIsRemoveCurV:false
                                    withDirection:VD_RIGHT];
    }

}

-(void)playVoice:(NSString*)voicePath
{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
    
    if(session == nil)
    {
        AS_LOG(@"Error creating session: %@", [sessionError description]);
    }
    else
        [session setActive:YES error:nil];
    NSError *playerError;
    NSData *SpeexData = [NSData dataWithContentsOfFile:voicePath];
    AS_LOG(@"playvoice %@",voicePath);
    NSData *NewPCMData = DecodeSpeexToWAVE(SpeexData);
    player = [[AVAudioPlayer alloc] initWithData:NewPCMData error:&playerError];
    player.delegate = self;
    AS_LOG(@"voice length is %f",player.duration);
    [player prepareToPlay];
    [player play];
}

-(void)PopGiftSheet
{
    iSheetType = CST_GIFT;
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@""
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"查看礼物",
                                  @"回礼",@"查看个人信息",@"我的礼物",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    actionSheet.tag = 1;
    [actionSheet showInView:self.view];
}

-(void)PopResendSheet
{
    iSheetType = CST_RESEND;
    
    UIActionSheet * myActionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                delegate:self
                                                       cancelButtonTitle:nil
                                                  destructiveButtonTitle:nil
                                                       otherButtonTitles:nil];
    
    [myActionSheet addButtonWithTitle:NSLocalizedString(@"重新发送", nil)];
    [myActionSheet addButtonWithTitle:NSLocalizedString(@"取消", nil)];
    myActionSheet.cancelButtonIndex = 1;
    myActionSheet.destructiveButtonIndex = 0;
    [myActionSheet showInView:self.view];

}

//?æÊ?Ê∑∑Ê?

#define KFacialSizeWidth  20
#define KFacialSizeHeight 20
#define MAX_WIDTH 175//转行的最大宽度
#define BEGIN_FLAG @"[/"
#define END_FLAG @"]"

-(void)getImageRange:(NSString*)message inArray:(NSMutableArray*)array {
    NSRange range=[message rangeOfString: BEGIN_FLAG];
    NSRange range1=[message rangeOfString: END_FLAG];
    if (range.length>0 && range1.length>0) {
        if (range.location > 0) {
            [array addObject:[message substringToIndex:range.location]];
            
            [array addObject:[message substringWithRange:NSMakeRange(range.location, range1.location+1-range.location)]];
            
            NSString *str=[message substringFromIndex:range1.location+1];
            [self getImageRange:str inArray:array];
        }else {
            NSString *nextstr=[message substringWithRange:NSMakeRange(range.location, range1.location+1-range.location)];
            if (![nextstr isEqualToString:@""]) {
                [array addObject:nextstr];
                
                NSString *str=[message substringFromIndex:range1.location+1];
                [self getImageRange:str inArray:array];
            }else {
                return;
            }
        }
        
    } else if (message != nil) {
        [array addObject:message];
    }
}

-(UIView *)getTextViewOnCell:(NSString *)message
{
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [self getImageRange:message inArray:array];
    UIView *returnView = [[UIView alloc] initWithFrame:CGRectZero];
    NSArray *data = array;
    UIFont *fon = [UIFont systemFontOfSize:16.0f];//字号
    CGFloat upX = 0;
    CGFloat upY = 0;
    CGFloat X = 0;
    CGFloat Y = 0;
    if (data) {
        for (int i=0;i < [data count];i++) {
            NSString *str=[data objectAtIndex:i];
            if ([str hasPrefix: BEGIN_FLAG] && [str hasSuffix: END_FLAG])
            {
                if (upX >= MAX_WIDTH)
                {
                    upY = upY + KFacialSizeHeight;
                    upX = 0;
                    X = MAX_WIDTH;
                    Y = upY;
                }
                NSString *imageName = [_emojiDic objectForKey:str];
                UIImageView *img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:imageName]];
                img.frame = CGRectMake(upX, upY, KFacialSizeWidth, KFacialSizeHeight);
                [returnView addSubview:img];
                upX=KFacialSizeWidth+upX;
                if (X<MAX_WIDTH) X = upX;
            } else {
                for (int j = 0; j < [str length]; j++) {
                    NSString *temp = [str substringWithRange:NSMakeRange(j, 1)];
                    if (upX >= MAX_WIDTH)
                    {
                        upY = upY + KFacialSizeHeight;
                        upX = 0;
                        X = MAX_WIDTH;
                        Y =upY;
                    }
                    CGSize size=[temp sizeWithFont:fon constrainedToSize:CGSizeMake(MAX_WIDTH, 40)];
                    UILabel *la = [[UILabel alloc] initWithFrame:CGRectMake(upX,upY,size.width,size.height)];
                    la.font = fon;
                    la.text = temp;
                    la.backgroundColor = [UIColor clearColor];
                    [returnView addSubview:la];
                    upX=upX+size.width;
                    if (X<MAX_WIDTH) {
                        X = upX;
                    }
                }
            }
        }
    }
    returnView.frame = CGRectMake(15.0f,1.0f, X, Y + KFacialSizeHeight);
    
    
    return returnView;
}

-(void)TelepthyFail
{
    [[ViewManager sharedViewManager] showFailHUDWithStatus:@"不能再次进入了耶"
                                                 withDelay:2
                                                  withView:self.view];
}

#pragma mark -
#pragma mark Table View DataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [DataControl shareControl].chatDS.currentChatArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0;
    if (indexPath.row >= 0 &&
        indexPath.row < [self.rowHeights count]) {
        height = [[self.rowHeights objectAtIndex:indexPath.row] floatValue];
    }
    
    height = height + 2*[ChatCell textMarginVertical] + 35.0f;
    return height;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
    ChatContentInfo *cci = nil;
    
    if ([indexPath section] == 0)
    {
        if ([DataControl shareControl].chatDS.currentChatArr != nil  &&
            [indexPath row] < [[DataControl shareControl].chatDS.currentChatArr count])
        {
            cci = [[DataControl shareControl].chatDS.currentChatArr objectAtIndex:[indexPath row]];
        }
        
    }
    
    NSString *CommentCellIdentifier = [NSString stringWithFormat:@"CommentCell%d%d"
                                              ,indexPath.section
                                              ,indexPath.row];
    
    if (cci != nil && cci.isSelf)
    {
        CommentCellIdentifier = [NSString stringWithFormat:@"%@self",CommentCellIdentifier];
    }
    
    if(cci.chatType == CT_GIFT)
    {
        ChatGiftCell *giftcell = (ChatGiftCell *)[tableView dequeueReusableCellWithIdentifier:CommentCellIdentifier];
        
        if (giftcell == nil || ![giftcell isKindOfClass:[ChatGiftCell class]]) {
            giftcell = [[ChatGiftCell alloc] initMessagingCellWithReuseIdentifier:CommentCellIdentifier];
        }
        
        if (giftcell != nil) {
            
            giftcell.cellType = cci.chatType;
            giftcell.iRow = indexPath.row;
            
            [self configureGiftCell:giftcell atIndexPath:indexPath];
        }
        
        return giftcell;
    }
    else
    {
	ChatCell *cell = (ChatCell*)[tableView dequeueReusableCellWithIdentifier:CommentCellIdentifier];
	if (cell == nil || ![cell isKindOfClass:[ChatCell class]])
    {
		cell = [[ChatCell alloc] initMessagingCellWithReuseIdentifier:CommentCellIdentifier];
	}
    
    if (cci != nil)
    {
        cell.cellType = cci.chatType;
        cell.iSection = indexPath.section;
        cell.iRow = indexPath.row;
        
        [self configureCell:cell atIndexPath:indexPath];
    }
    
        
        
        return cell;
    }
    
}

-(void)configureCell:(id)cell atIndexPath:(NSIndexPath *)indexPath{
    ChatCell* ccell = (ChatCell*)cell;
    ChatContentInfo *cci = nil;
    if ([DataControl shareControl].chatDS.currentChatArr != nil  &&
        [indexPath row] < [[DataControl shareControl].chatDS.currentChatArr count])
    {
        cci = [[DataControl shareControl].chatDS.currentChatArr objectAtIndex:[indexPath row]];
    }
    
    if (cci == nil) {
        return;
    }
    
    ccell.cellType = cci.chatType;
    ccell.iSection = indexPath.section;
    ccell.iRow = indexPath.row;
    ccell.ccinfo = cci;
    
    if (cci.isSelf) {
        ccell.sent = YES;
        NSString *strurl = [[DataControl shareControl] SearchHeadImage:
                            [DataControl shareControl].personDS.uinfo.mail];
        if (![strurl isEqual: @""])
        {
            ccell.avatarImageView.image = [UIImage imageWithContentsOfFile:strurl];
        }else{
            ccell.avatarImageView.image = [UIImage imageNamed:@"default_head.png"];
        }
        
        ccell.StateLabel.hidden = NO;
        
    } else {
        ccell.sent = NO;
        NSString *imageurl = @"";
        
        if ([DataControl shareControl].currentFI != nil)
        {
            imageurl = [[DataControl shareControl] SearchHeadImage:
                        [DataControl shareControl].currentFI.mail];
        }
        
        if (![imageurl isEqual: @""])
        {
            ccell.avatarImageView.image = [UIImage imageWithContentsOfFile:imageurl];
        }
        else
        {
            ccell.avatarImageView.image = [UIImage imageNamed:@"default_head.png"];
        }
        
        if (cci.chatType == CT_VOICE) {
            if (cci.ichatReadState != CRS_UNREAD) {
                ccell.StateLabel.hidden = YES;
            }
            else
            {
                ccell.StateLabel.hidden = NO;
            }
        }
        else
        {
            ccell.StateLabel.hidden = YES;
        }
    }
    ccell.message = cci.strtext;
    ccell.timeLabel.text = cci.GetTimeString;
    
    switch (ccell.cellType) {
        case CT_TEXT:
        case CT_TELEPATHY:
        {
            if (indexPath.row >= 0 &&
                indexPath.row < [self.chatArray count]) {
                [ccell.textView removeFromSuperview];
                UILabel *returnView =  [self.chatArray objectAtIndex:indexPath.row];
                ccell.textView = returnView;
            }
        }
            break;
        case  CT_VOICE:
        {
            ccell.audioControlView.tag = indexPath.row;
            if (indexPath.row == playingVoiceIndex) {
                ccell.audioControlView.image = [UIImage imageNamed:@"btn_audioPause_press.png"];
            }else{
                ccell.audioControlView.image = [UIImage imageNamed:@"btn_audioPlay_press.png"];
            }
            
            int al = cci.audioPlayLength;
            ccell.voiceTimeLabel.text = [NSString stringWithFormat:@"%d\"",al];
        }
            break;
        case CT_IMAGE:
        {
            UIImage * tmpImage = [UIImage imageWithData:
                                  [NSData dataWithContentsOfFile:
                                   cci.strtext]];
            if (tmpImage.size.width < tmpImage.size.height) {
                float width = tmpImage.size.width*(100.0 / tmpImage.size.height);
                ccell.contentImgView.image = OriginImage(tmpImage, CGSizeMake(width, 100));
            }else{
                float height = tmpImage.size.height*(100.0 / tmpImage.size.width);
                ccell.contentImgView.image = OriginImage(tmpImage, CGSizeMake(100, height));
            }
            
        }
            break;
            
        default:
            break;
    }
    
    ccell.StateLabel.text = [self GetChatStateByType:cci.ichatReadState];
    ccell.StateLabel.backgroundColor = [self GetStateColorByType:cci.ichatReadState];
    
}

-(NSString *)GetChatStateByType:(int)itype
{
    NSString *strtype = @"";
    
    switch (itype) {
        case CRS_READ:
        {
            strtype = @"已阅读";
        }
            break;
        case CRS_ARRIVE:
        {
            strtype = @"已送达";
        }
            break;
        case CRS_SENDING:
        {
            strtype = @"发送中";
        }
            break;
        case CRS_SENDSUCCESS:
        {
            strtype = @"已发送";
        }
            break;
            case CRS_SENDFAIL:
        {
            strtype = @"失败";
        }
            break;
            case CRS_UNREAD:
        {
            strtype = @"未读";
        }
            break;
            case CRS_SHIELD:
        {
            strtype = @"被屏蔽";
        }
            break;
            
        default:
            break;
    }
    
    return strtype;
}

-(UIColor *)GetStateColorByType:(int)itype
{
    UIColor *scolor = [UIColor clearColor];
    
    switch (itype) {
        case CRS_SENDING:
        {
            scolor = COLOR_CHATSTATE_SENDING;
        }
            break;
            case CRS_ARRIVE:
        case CRS_SENDSUCCESS:
        {
            scolor = COLOR_CHATSTATE_SEND;
        }
            break;
        case CRS_SENDFAIL:
        case CRS_SHIELD:
        case CRS_UNREAD:
        {
            scolor = COLOR_CHATSTATE_FAIL;
        }
            break;
        case CRS_READ:
        {
            scolor = COLOR_CHATSTATE_READ;
        }
            break;
        default:
            break;
    }
    
    return scolor;
}

-(void)configureGiftCell:(id)cell atIndexPath:(NSIndexPath *)indexPath{
    ChatGiftCell* ccell = (ChatGiftCell*)cell;
    ChatContentInfo *cci = nil;
    ccell.iRow = indexPath.row;
    if ([DataControl shareControl].chatDS.currentChatArr != nil  &&
        [indexPath row] < [[DataControl shareControl].chatDS.currentChatArr count])
    {
        cci = [[DataControl shareControl].chatDS.currentChatArr objectAtIndex:[indexPath row]];
    }
    
    if (cci == nil) {
        return;
    }
    
    ccell.cellType = cci.chatType;
    
    if (cci.isSelf) {
        ccell.sent = YES;
        NSString *strurl = [[DataControl shareControl] SearchHeadImage:
                            [DataControl shareControl].personDS.uinfo.mail];
        if (![strurl isEqual: @""])
        {
            ccell.avatarImageView.image = [UIImage imageWithContentsOfFile:strurl];
        }else{
            ccell.avatarImageView.image = [UIImage imageNamed:@"default_head.png"];
        }
        
        FirendInfo *finfo = [[DataControl shareControl] SearchInfo:cci.strsendmail];
        GiftInfoDataInfo *ginfo = [[DataControl shareControl].giftInfoDS getGiftInfoByID:cci.giftid];
        
        if (finfo != nil && ginfo != nil) {
            NSString *strtext = [NSString stringWithFormat:@"你送给%@%d个%@耶",
                                 finfo.name,
                                 cci.igiftNum,
                                 ginfo.strgiftname];
            
            ccell.taxtLabel.text = strtext;
        }
        
        ccell.StateLabel.hidden = NO;
        
    } else {
        ccell.sent = NO;
        NSString *imageurl = @"";
        
        if ([DataControl shareControl].currentFI != nil)
        {
            imageurl = [[DataControl shareControl] SearchHeadImage:
                        [DataControl shareControl].currentFI.mail];
        }
        
        if (![imageurl isEqual: @""])
        {
            ccell.avatarImageView.image = [UIImage imageWithContentsOfFile:imageurl];
        }
        else
        {
            ccell.avatarImageView.image = [UIImage imageNamed:@"default_head.png"];
        }
        
        GiftInfoDataInfo *ginfo = [[DataControl shareControl].giftInfoDS getGiftInfoByID:cci.giftid];
        FirendInfo *finfo = [[DataControl shareControl] SearchInfo:cci.strsendmail];
        
        if (finfo != nil && ginfo != nil) {
            NSString *strtext = [NSString stringWithFormat:@"%@送给你%d个%@耶",
                                 finfo.name,
                                 cci.igiftNum,
                                 ginfo.strgiftname];
            
            ccell.taxtLabel.text = strtext;
        }
        
        ccell.StateLabel.hidden = YES;
    }
    ccell.timeLabel.text = cci.GetTimeString;
    
    NSString *strgiftimagepath = [[DataControl shareControl].giftInfoDS searchGiftImagePath:cci.giftid];
    if (strgiftimagepath != nil &&
        ![strgiftimagepath isEqualToString:@""]) {
        ccell.giftImageView.image = [UIImage imageWithContentsOfFile:strgiftimagepath];
    }
    else
    {
        ccell.giftImageView.image = [UIImage imageNamed:@"gift_default.png"];
    }
    
   
    ccell.StateLabel.text = [self GetChatStateByType:cci.ichatReadState];
    ccell.StateLabel.backgroundColor = [self GetStateColorByType:cci.ichatReadState];
}

#pragma mark -
#pragma mark Table View Delegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark AVAudioPlayerDelegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{
    playingVoiceIndex = -1;
    [self.mtablev reloadData];
}

#pragma mark UIActionSheetDelegate -
-(void)actionSheetCancel:(UIActionSheet *)actionSheet
{
}

-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    switch (iSheetType) {
        case CST_GIFT:
        {
            switch (buttonIndex) {
                case 0:
                {
                    if ([DataControl shareControl].giftMessageDS.curSelectInfo != nil) {
                        NSString *strid =
                        [DataControl shareControl].giftMessageDS.curSelectInfo.strgiftid;
                        
                        [ViewManager sharedViewManager].giftshowvc.ginfo =
                        [[DataControl shareControl].giftInfoDS getGiftInfoByID:strid];
                        
                        [ViewManager sharedViewManager].giftshowvc.isendcount =
                        [DataControl shareControl].giftMessageDS.curSelectInfo.igiftcount;
                        
                        [[ViewManager sharedViewManager] showView:VI_GIFT_SHOW
                                                 withIsRemoveCurV:false
                                                    withDirection:VD_NULL];
                    }
                }
                    break;
                    case 1:
                {
                    [[netManager sharedNetManager].sendp SendMainIndex:ID_MI_GIFT
                                                       WithSecondIndex:GI_GET];
                    
                    [DataControl shareControl].giftInfoDS.strSenderMail =
                    [DataControl shareControl].giftMessageDS.curSelectInfo.strsendermail;
                    
//                    [[ViewManager sharedViewManager] showView:VI_GIFTLIST
//                                             withIsRemoveCurV:false
//                                                withDirection:VD_RIGHT];
                    
                    [[DataControl shareControl].giftInfoDS SetShowArrByListID:1];
                    
                    [[ViewManager sharedViewManager] showView:VI_GIFTLISTINFO
                                             withIsRemoveCurV:false
                                                withDirection:VD_RIGHT];
                    
                    [[netManager sharedNetManager].sendgiftLL sendGiftLL:1];
                    
                    [[netManager sharedNetManager].sendPersonRC sendReadCoin];
                }
                    break;
                    case 2:
                {
                    [DataControl shareControl].currentFI = [[DataControl shareControl] SearchInfo:
                        [DataControl shareControl].giftMessageDS.curSelectInfo.strsendermail];
                    
                    [[ViewManager sharedViewManager] showView:VI_PERSONINFO
                                             withIsRemoveCurV:false
                                                withDirection:VD_RIGHT];
                }
                    break;
                    case 3:
                {
                    [[DataControl shareControl].giftStroageDS delAllArr];
                    
                    [[netManager sharedNetManager].sendgiftStroage
                        sendGiftGetTheStroage:[DataControl shareControl].personDS.uinfo.mail];
                    
                    
                    [[ViewManager sharedViewManager] showView:VI_GIFT_STROAGE
                                             withIsRemoveCurV:false
                                                withDirection:VD_RIGHT];
                }
                    break;
                default:
                    break;
            }
        }
            break;
            case CST_PHOTO:
        {
            switch (buttonIndex) {
                case 0:{
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                        UIImagePickerController *picker=[[UIImagePickerController alloc]init];
                        picker.sourceType=UIImagePickerControllerSourceTypeCamera;
                        picker.delegate=self;
                        [self presentViewController:picker animated:YES completion:nil];
                    }
                }
                    break;
                case 1:{
                    UIImagePickerController *picker=[[UIImagePickerController alloc]init];
                    picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
                    picker.delegate=self;
                    [self presentViewController:picker animated:YES completion:nil];
                }
                    break;
                case 2:
                    break;
                default:
                    break;
            }
        }
            break;
        case CST_RESEND:
        {
            switch (buttonIndex)
            {
                case 0:
                {
                    if ([DataControl shareControl].chatDS.reSendInfo != nil) {
                        
                        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
                        NSTimeInterval a=[dat timeIntervalSince1970] * 1000;
                        long long aa = a;
                        
                        [DataControl shareControl].chatDS.reSendInfo.strChatDate =
                        [NSString stringWithFormat:@"%lld", aa];
                        
                        [LogicControl sharedLogicControl].icurSequence =
                        [DataControl shareControl].chatDS.reSendInfo.iSequence;
                        
                        [DataControl shareControl].chatDS.reSendInfo.ichatReadState = CRS_SENDING;
                        
                        [StateFailDic setObject:[NSNumber numberWithInt:0]
                                         forKey:
                         [NSNumber numberWithInt:[DataControl shareControl].chatDS.reSendInfo.iSequence]];
                        
                        [[DataControl shareControl].chatDS SetSendChatContent:
                         [DataControl shareControl].chatDS.reSendInfo.strtext];
                        
                        [self.mtablev reloadData];
                        
                        switch ([DataControl shareControl].chatDS.reSendInfo.chatType) {
                            case CT_TEXT:
                            {
                                [[DataControl shareControl].LCDS addLogicCommand:LC_SENDTEXT];
                            }
                                break;
                            case CT_IMAGE:
                            {
                                [[DataControl shareControl].LCDS addLogicCommand:LC_SENDIMAGE];
                            }
                                break;
                            case CT_VOICE:
                            {
                                [[DataControl shareControl].LCDS addLogicCommand:LC_SENDVOICE];
                            }
                                break;
                            default:
                                break;
                        }
                    }
                }
                break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
    
}

#pragma mark UIImagePickerControllerDelegate -
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissModalViewControllerAnimated:YES];
    
    UIImage *selectedImage = [info valueForKey:UIImagePickerControllerOriginalImage];
    if ((selectedImage.size.width > WINDOW_WIDTH)||(selectedImage.size.height > WINDOW_HIGTH))
    {
        CGFloat width = selectedImage.size.width;
        CGFloat height = selectedImage.size.height;
        
        float verticalRadio = WINDOW_HIGTH*1.0/height;
        float horizontalRadio = WINDOW_WIDTH*1.0/width;
        
        float radio = 1;
        if(verticalRadio>1 && horizontalRadio>1)
        {
            radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;
        }
        else
        {
            radio = verticalRadio < horizontalRadio ? verticalRadio : horizontalRadio;
        }
        
        width = width*radio; 
        height = height*radio;
        
        selectedImage = [selectedImage transformWidth:width height:height];
    }
    
    [self sendChatContent:[[FileManager shareControl] saveChatImage:selectedImage]
                 withType:CT_IMAGE
          withAudioLength:-1];
    
    [[DataControl shareControl].LCDS addLogicCommand:LC_SENDIMAGE];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - key board -
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [self autoMovekeyBoard:keyboardRect.size.height];
    [self scrollTableViewToBottom];
}

-(void)keyboardWillHide:(NSNotification *)notification
{
    NSDictionary* userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [self autoMovekeyBoard:0];
}

-(void)autoMovekeyBoard:(float)high
{
    if (high > 0) {
      self.mtablev.frame = CGRectMake(0.0f, TOPBAR_HIGHT, WINDOW_WIDTH,(float)(WINDOW_HIGTH - high - CHATVIEW_INPUTBAR_HEIGHT*2 - NATIVEBAR_HIGTH));
    }else{
        self.mtablev.frame = CGRectMake(0, TOPBAR_HIGHT, WINDOW_WIDTH,
                                        WINDOW_HIGTH - CHATVIEW_INPUTBAR_HEIGHT*2
                                        - NATIVEBAR_HIGTH);
    }
    
    float chatInputPOSY = self.mtablev.frame.origin.y + self.mtablev.frame.size.height;
    
    chatInput.frame = CGRectMake(0.0f, chatInputPOSY, WINDOW_WIDTH, 44.0f);
}

- (void)scrollTableViewToBottom
{
    NSInteger sections = [self.mtablev numberOfSections];
    if (sections < 1) return;
    NSInteger rows = [self.mtablev numberOfRowsInSection:sections - 1];
    if (rows < 1) return;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rows - 1 inSection:sections - 1];
    [self.mtablev scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}

- (void)showEmojiInput:(id)sender
{
    if (chatInput.textView.inputView == nil) {
        chatInput.textView.inputView = emojiInputView;
        [chatInput.emojiButton setBackgroundImage:[UIImage imageNamed:@"Chat_Footer_Keyboard_Icon.png"] forState:UIControlStateNormal];
    }else{
        chatInput.textView.inputView = nil;
        [chatInput.emojiButton setBackgroundImage:[UIImage imageNamed:@"Chat_Footer_Smiley_Icon.png"] forState:UIControlStateNormal];
    }
    
    [chatInput.textView reloadInputViews];
}

- (void)inputEmoji:(NSNotification *)notification
{
    if ([ViewManager sharedViewManager].currentVC ==
        [ViewManager sharedViewManager].chatvc) {
        NSNumber *index = (NSNumber *)[notification object];
        NSMutableString *faceString = [[NSMutableString alloc]initWithString:chatInput.textView.text];
        [faceString appendString:[emojiInputView._faceMap objectForKey:[NSString stringWithFormat:@"%03d",[index intValue]]]];
        [chatInput setText:faceString];
    }
    
}

- (void)deleteEmoji:(NSNotification *)notification
{
    if ([ViewManager sharedViewManager].currentVC ==
        [ViewManager sharedViewManager].chatvc) {
    NSString *inputString;
    inputString = chatInput.textView.text;
    
    NSString *string = nil;
    NSInteger stringLength = inputString.length;
    if (stringLength > 0) {
        if ([@"]" isEqualToString:[inputString substringFromIndex:stringLength-1]]) {
            if ([inputString rangeOfString:@"["].location == NSNotFound){
                string = [inputString substringToIndex:stringLength - 1];
            } else {
                string = [inputString substringToIndex:[inputString rangeOfString:@"[" options:NSBackwardsSearch].location];
            }
        } else {
            string = [inputString substringToIndex:stringLength - 1];
        }
    }
    [chatInput setText:string];
        }
}

- (void)dismissKeyboard
{
    [chatInput.textView resignFirstResponder];
}

-(void)ShowSendGift
{
    [self dismissKeyboard];
    
    [[netManager sharedNetManager].sendp SendMainIndex:ID_MI_GIFT
                                       WithSecondIndex:GI_GET];
    
    [DataControl shareControl].giftInfoDS.strSenderMail =
    [DataControl shareControl].currentFI.mail;
    
    if (![[DataControl shareControl].currentFI.mail isEqualToString:@"jingling"]) {
//        [[ViewManager sharedViewManager] showView:VI_GIFTLIST
//                                 withIsRemoveCurV:false
//                                    withDirection:VD_RIGHT];
        
        [[DataControl shareControl].giftInfoDS SetShowArrByListID:1];
        
        [[ViewManager sharedViewManager] showView:VI_GIFTLISTINFO
                                 withIsRemoveCurV:false
                                    withDirection:VD_RIGHT];
        
        [[netManager sharedNetManager].sendgiftLL sendGiftLL:1];
        
        [[netManager sharedNetManager].sendPersonRC sendReadCoin];
    }
    else
    {
        [[ViewManager sharedViewManager] showFailHUDWithStatus:@"亲，碰碰精灵不要礼物哦"
                                                     withDelay:2
                                                      withView:self.view];
    }
}

-(void)setVoiceCannel
{
    voiceTipsView.bcancel = true;
}

-(void)setVoiceSuccee
{
    voiceTipsView.bcancel = false;
}

@end
